﻿using DataCollection.ChangeCode;
using RQX.Common.Core.Extension;
using RQX.Common.Core.Logger;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataCollection.SimulateTool
{
    public partial class Simulate : Form
    {
        private bool IsCircleInsert = false;
        public Simulate()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Simulate_Load(object sender, EventArgs e)
        {
            var typeList = CodeInfo.list.GroupBy(k => k.DeviceType).Select(k => k.Key);
            cklist_type.Items.Clear();
            typeList.ForEach(type =>cklist_type.Items.Add(type));
            BeginShow();
        }
        /// <summary>
        /// checkList选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cklist_type_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGridView();
        }
        /// <summary>
        /// 绑定grid
        /// </summary>
        private void BindGridView()
        {
            var items = cklist_type.CheckedItems;
            List<string> typeList = new List<string>();
            foreach (var item in items)
            {
                typeList.Add(item.ToString());
            }

            var list = CodeInfo.list.Where(k => typeList.Contains(k.DeviceType));
            grid.Rows.Clear();
            list.ForEach(item =>
            {
                grid.Rows.Add(item.IsUse, item.DeviceType, item.Code, item.Name, item.Desc, item.Low, item.High, item.IsRandom, item.DefaultValue);
            });
        }
        /// <summary>
        /// grid修改后事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            var value = grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
            var code = Convert.ToInt32(grid.Rows[e.RowIndex].Cells["dgv_code"].Value);
            var obj = CodeInfo.list.Find(k => k.Code == code);
            var name = grid.Columns[e.ColumnIndex].Name;
            switch (name)
            {
                case "dgv_use": obj.IsUse = (bool)value; break;
                case "dgv_random": obj.IsRandom = (bool)value; break;
                case "dgv_default": obj.DefaultValue = value?.ToString(); break;
            }
            CodeInfo.Save();
        }
        /// <summary>
        /// 开始生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_start_Click(object sender, EventArgs e)
        {
            if (IsCircleInsert)
            {
                IsCircleInsert = false;
                btn_start.Text = "开始生成";
            }
            else
            {
                var items = cklist_type.CheckedItems;
                List<string> typeList = new List<string>();
                foreach (var item in items)
                {
                    typeList.Add(item.ToString());
                }

                var list = CodeInfo.list.Where(k => typeList.Contains(k.DeviceType) && k.IsUse);
                foreach (var item in list)
                {
                    if (item.IsRandom == false && item.DefaultValue.IsNullOrEmpty())
                    {
                        FormUtils.ShowMsg($"{item.Name}未设置随机插入，又未设置默认值！");
                        return;
                    }
                }
                btn_start.Text = "停止生成";
                DoCircleInsert(list);
            }
        }
        /// <summary>
        /// 循环插入
        /// </summary>
        /// <param name="list"></param>
        private void DoCircleInsert(IEnumerable<CodeInfo> list)
        {
            IsCircleInsert = true;
            Task.Run(() =>
            {
                Random random = new Random();
                while (IsCircleInsert)
                {
                    MYSQLDB.ShowMsgHandler = ShowRealTimeMsg;
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    list.ForEach(item =>
                    {
                        var low = Convert.ToInt32(item.Low);
                        var high = Convert.ToInt32(item.High);
                        var value = item.IsRandom ? random.Next(low, high).ToString() : item.DefaultValue;
                        dic.Add($"{item.Code}Я{item.Name}", value);
                        ShowRealTimeMsg($"模拟数据：{item.Code}\t{item.Name}\t{value}");
                    });
                    MYSQLDB.BuildDataFormart(dic, "");
                    Thread.Sleep(1000);
                }
            });
        }
        #region 日志信息
        private ConcurrentQueue<string> queueMsg = new ConcurrentQueue<string>();
        public void ShowRealTimeMsg(string msg)
        {
            LogUtils.WriteDebugLog($"{DateTime.Now:HH:mm:ss.fff}  Simulate:{msg}\n");
            if (msg.Length > 200)
            {
                msg = msg.Substring(0, 200);
            }
            queueMsg.Enqueue($"{DateTime.Now:HH:mm:ss.fff}  {msg}\n");
        }
        private void BeginShow()
        {
            txt_log.Text = "";
            Task.Run(() =>
            {
                while (true)
                {
                    Thread.Sleep(1000);
                    if (txt_log.Text.Length > 20000)
                    {
                        txt_log.Text = txt_log.Text.Substring(0, 5000);
                    }
                    while (queueMsg.TryDequeue(out var msg))
                    {
                        txt_log.Text = msg + txt_log.Text;
                    }
                }
            });
        }
        #endregion
    }
}
